/*
 * 作者: 侯晓宇
 * 时间: 2017-01-11 
 * 说明：
 * Copyright (c) 2016-2017 中研沃兮
 */
define(function(require) {

	var c = require('app/utils/CommonUtils');
	var s = {};

	//窗体间传递消息，发送方
	//wfName - 窗体名称
	//eventName - 事件名称
	//msg - 具体内容
	//事件 = wfName+"_"+eventName 
	//例如：CreateRoomWin_updateCover，CreateRoomWin为窗体名称，updateCover为事件名称
	s.send = function(wfName, eventName, msg) {
		c.debug("send_event_name",wfName + "_" + eventName);
		c.debug("send_event_msg",msg);
		api.sendEvent({
			name: wfName + "_" + eventName,
			extra: msg
		});
	}

	//窗体间传递消息，注册方
	//wfName - 窗体名称
	//eventName - 事件名称
	//once - 事件是否仅接收一次，默认为false
	//事件 = wfName+"_"+eventName 
	//例如：CreateRoomWin_updateCover，CreateRoomWin为窗体名称，updateCover为事件名称
	s.listen = function(wfName, eventName, once, callback_func) {
		return new Promise(function(resolve, reject) {
			var _once = once;
			var name = wfName + "_" + eventName;
			if (c.isNull(_once)) {
				_once = false;
			}
			c.debug("listen_event_name",name);
			
			api.addEventListener({
				name: name
			}, function(ret, err) {
				
				if (_once) {
					api.removeEventListener({
						name: name
					});
				}
				if (ret) {
					c.debug("receive_event_name",name);
					c.debug("receive_event_msg",ret.value);

					if (!c.isNull(callback_func)) {
						callback_func(ret.value);
					} else {
						resolve(ret.value);
					}
				}
			});
		});
	}

	s.listenGather = function(callback_func) {

		var from_win_to_frm_name = "_from_" + api.winName + "_to_" + api.frameName + "_gather";
		api.addEventListener({
			name: from_win_to_frm_name
		}, function(ret, err) {
			if (ret) {
				callback_func();
			}
		});

	}
	s.gatherFrmVal = function(frmName) {

		return new Promise(function(resolve, reject) {

			var from_frm_to_win_name = "_from_" + frmName + "_to_" + api.winName + "_gather";
			api.addEventListener({
				name: from_frm_to_win_name
			}, function(ret, err) {
				if (ret) {
					resolve(ret.value);
				}
			});

			var from_win_to_frm_name = "_from_" + api.winName + "_to_" + frmName + "_gather";
			api.sendEvent({
				name: from_win_to_frm_name
			});

		});
	}

	s.sendFrmVal = function(msg) {
		var from_frm_to_win_name = "_from_" + api.frameName + "_to_" + api.winName + "_gather";
		api.sendEvent({
			name: from_frm_to_win_name,
			extra: msg
		});
	}
	return s;
});